package View;

import Dao.User;
import Dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        // 1. 获取用户名密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        // 2. 判断用户名密码是否为空
        if(username == null || "".equals(username) || password == null || "".equals(password)){
            resp.getWriter().write("<h3>用户名或者密码为空,登录失败!</h3>");
            return;
        }
        // 3. 判断输入的用户名或者密码是否正确
        UserDao userDao = new UserDao();
        User user = userDao.selectByName(username);
        if(user == null){
            resp.getWriter().write("<h3>用户名或者密码错误,登录失败!</h3>");
            return;
        }

        if(!user.getPassWord().equals(password)){
            resp.getWriter().write("<h3>用户名或者密码错误,登录失败!</h3>");
            return;
        }
        // 4. 登陆成功,就把user存到HttpSession中
        HttpSession session = req.getSession(true);
        session.setAttribute("user",user);
        // 5. 重定向到主页
        resp.sendRedirect("index.html");
    }
}
